package cn.edu.sdjzu.xg.bysj.service;


import cn.edu.sdjzu.xg.bysj.dao.SchoolDao;
import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.util.Condition;
import cn.edu.sdjzu.xg.bysj.util.JdbcHelper;
import cn.edu.sdjzu.xg.bysj.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService=new SchoolService();


	public static SchoolService getInstance(){
		return schoolService;
	}

	public Collection<School> findAll(Pagination pagination, List<Condition> conditionList) throws SQLException, BysjException {
		return schoolDao.findAll(pagination, conditionList);
	}

	//读取所有记录，不分布，不加条件，很少见，仅作为示例用
	public Collection<School> findAll() throws SQLException, BysjException {
		return schoolDao.findAll(null, null);
	}
	public School find(Integer id) throws SQLException, BysjException {
		return schoolDao.find(id);
	}

	public boolean update(School school) throws SQLException {
		return schoolDao.update(school);
	}

	public boolean add(School school) throws SQLException {
		return schoolDao.add(school);
	}

	public boolean delete(Integer id) throws SQLException, BysjException {
		School schoolToDelete = this.find(id);
		return this.delete(schoolToDelete);
	}

	public boolean delete(School school) throws SQLException, BysjException {
		//获得所有下一级单位（Department）的数量
		int countDepartmentsOfSchool = DepartmentService.getInstance().countAll(school);
		//若没有二级单位，则能够删除
		if(countDepartmentsOfSchool==0){
			return schoolDao.delete(school);
		}else {
			throw new BysjException(school.getDescription() + "仍然有下属系，不能删除");
		}
	}

	public int count() throws SQLException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		JdbcHelper.close(connection);
		return SchoolDao.getInstance().count(connection);
	}

	public static void main(String[] args) throws Exception {

//		for(int i = 3; i < 24; i++) {
//			School civilSchool = new School(""+i, ""+i, "");
//			SchoolService.getInstance().add(civilSchool);
//		}
//		SchoolService.getInstance().add(civilSchool);

//		School mgtSchool = SchoolService.getInstance().find(5);
//		SchoolService.getInstance().delete(mgtSchool);
	}

}
